from flask import request, jsonify
from flask_restx import Resource, Namespace
from ..services.auth import AuthService
from .. import api

# 创建认证命名空间
ns = api.namespace('auth', description='认证相关接口')

@ns.route('/register')
class Register(Resource):
    def post(self):
        """用户注册接口"""
        data = request.get_json()
        username = data.get('username')
        email = data.get('email')
        password = data.get('password')
        
        if not all([username, email, password]):
            return {'message': '请提供完整的注册信息'}, 400
        
        try:
            user = AuthService.create_user(username, email, password)
            return {'message': '注册成功', 'user': user.to_dict()}, 201
        except Exception as e:
            return {'message': str(e)}, 400

@ns.route('/login')
class Login(Resource):
    def post(self):
        """用户登录接口"""
        data = request.get_json()
        username = data.get('username')
        password = data.get('password')
        
        if not all([username, password]):
            return {'message': '请提供用户名和密码'}, 400
        
        user = AuthService.authenticate_user(username, password)
        if not user:
            return {'message': '用户名或密码错误'}, 401
        
        token = AuthService.generate_token(user)
        return {
            'message': '登录成功',
            'token': token,
            'user': user.to_dict()
        }

@ns.route('/me')
class UserInfo(Resource):
    def get(self):
        """获取当前用户信息"""
        auth_header = request.headers.get('Authorization')
        if not auth_header:
            return {'message': '未提供认证令牌'}, 401
        
        try:
            token = auth_header.split(' ')[1]
            user = AuthService.verify_token(token)
            if not user:
                return {'message': '无效的认证令牌'}, 401
            return user.to_dict()
        except Exception:
            return {'message': '无效的认证令牌'}, 401